<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input :disabled="formDisabled" v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.proposer"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart placeholder="请选择申请部门" :disabled="formDisabled" v-model="model.proposerDeptId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart placeholder="请选择申请单位" :disabled="formDisabled" v-model="model.applicant" />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input placeholder="请选择团队" :disabled="formDisabled" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="期望到货时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expectUseTime">
                  <!-- <j-date :disabled="formDisabled" placeholder="请选择期望到货时间" v-model="model.expectUseTime" :show-time="true"
                          date-format="YYYY-MM-DD HH:mm" style="width: 100%" /> -->
                  <a-date-picker
                    style="width: 100%"
                    :disabled="formDisabled"
                    placeholder="请选择期望到货时间"
                    @change="handleExpectUseTimeChange"
                    v-model="model.expectUseTime"
                    :showTime="true"
                    :disabled-date="disabledExpectUseTime"
                    format="YYYY-MM-DD HH:mm"
                    :getCalendarContainer="(node)=>{return node.parentNode}"
                  />
                </a-form-model-item>
              </a-col>
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item label="是否紧急" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isUrgency">-->
              <!--                  <j-dict-select-tag :disabled="formDisabled" type="radio" disabled v-model="model.isUrgency" dictCode="YES_OR_NO" placeholder="请选择是否紧急" />-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <a-col :span="8">
                <a-form-model-item label="定点供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isSupplier">
                  <j-dict-select-tag :disabled="formDisabled" type="radio" v-model="model.isSupplier" dictCode="YES_OR_NO" placeholder="请选择定点供应商" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroadType">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.provisionBroadType"
                    dictCode="provision_broad_type"
                    placeholder="请选择采购大类"
                    @input="isHideBusinessSegment" />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="物料类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
                  <a-select
                    v-model="model.provisionBroad"
                    :disabled="formDisabled"
                    placeholder="请选择物料类别"
                    :showSearch="true"
                    :allowClear="true"
                    :filterOption="filterOption"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                    @change="handleChange"
                  >
                    <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购总预算（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBudgetAmount">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.purchaseBudgetAmount"
                    placeholder="请输入采购总预算"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="showBusinessSegment">
                <a-form-model-item label="所属业务板块" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessSegment">
                  <!--                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.businessSegment" dictCode="business_segment"  placeholder="请选择所属业务板块"   />-->
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.businessSegment" dictCode="new_business_segment" placeholder="请选择所属业务板块" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="showBusinessSegment">
                <a-form-model-item label="紧急采购" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="urgentStatus">
                  <j-dict-select-tag :disabled="formDisabled" type="radio" v-model="model.urgentStatus" dictCode="urgent_status" placeholder="请选择紧急采购" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="采购事由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseReason">
                  <!-- <a-input :disabled="formDisabled" :max-length="500" v-model="model.purchaseReason" placeholder="请输入采购事由" ></a-input> -->
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.purchaseReason" rows="4" placeholder="请输入采购事由"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- 物料明细 -->
          <a-collapse-panel key="2" header="物料明细">
            <a-row :gutter="48">
              <erp-purchase-apply-form-detail-list ref="purchaseApply" :disabled="formDisabled" :provisionBroad="model.provisionBroad" @applyDetailData="applyDetailData"/>
            </a-row>
          </a-collapse-panel>
          <!-- 附件信息 -->
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpPurchaseApplyFormPrint id="pruchaseContent" v-if="formBpm" class="print_style" :formData="model" :formDataHistory="formData"></ErpPurchaseApplyFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { viewFile } from '@/utils/util'
  import ViewFileModal from '@/views/scy/components/ViewFileModal'
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import ErpPurchaseApplyFormDetailList from './reference/ErpPurchaseApplyFormDetailList';
import { preventSelection } from '@fullcalendar/core';
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import Print from '@/utils/print/printarea.js';

  import ErpPurchaseApplyFormPrint from './ErpPurchaseApplyFormPrint.vue';
  export default {
    name: 'ErpPurchaseApplyFormForm',
    mixins: [viewFile],
    components: {
      ViewFileModal,
      SelectTeamInput,
      SelectUserByDep,
      ErpPurchaseApplyFormDetailList,
      CommonFlowList,
      ErpPurchaseApplyFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        modelExpectUseTime: null,
        activeKey: ['1', '2', '3'],
        model: {
          checkStatus: 0,
          isUrgency: '1',
          // businessSegment: 'ZLYWYWBKFZR',
          purchaseBill: null
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          teamId: [
              { required: true, message: '请选择团队!', trigger: 'change' }
          ],
          // isUrgency: [
          //     { required: true, message: '请选择是否紧急!', trigger: 'blur' }
          // ],
          expectUseTime: [
              { required: true, message: '请选择期望到货时间!', trigger: 'change' }
          ],
          purchaseReason: [
              { required: true, message: '请输入采购事由!', trigger: 'blur' }
          ],
          // 物料类别
          provisionBroad: [
              { required: true, message: '请选择物料类别!', trigger: 'blur' }
          ],
          provisionBroadType: [
            { required: true, message: '请选择采购大类!', trigger: 'change' }
          ],
          isSupplier: [
              { required: true, message: '请选择定点供应商!', trigger: 'blur' }
          ],
          businessSegment: [
              { required: true, message: '请选择所属业务板块!', trigger: 'blur' }
          ],
          urgentStatus: [
            { required: true, message: '请选择紧急采购!', trigger: 'change' }
          ],
          purchaseBudgetAmount: [
              { required: true, message: '请输入采购总预算!', trigger: 'blur' }
          ]
        },
        url: {
          add: '/api/erp/purchase/procurement/erpPurchaseApplyForm/add',
          edit: '/api/erp/purchase/procurement/erpPurchaseApplyForm/edit',
          queryById: '/api/erp/purchase/procurement/erpPurchaseApplyForm/queryById',
          gainBillNo: '/api/erp/purchase/procurement/erpPurchaseApplyForm/gainBillNo',
          queryProvisionBroadList: '/api/erp/purchase/material/erpMaterialCategory/queryAllParent'
        },
        details: [],
        provisionBroadList: [], // 采购大类
        provisionBroadups: null,
        userName: '',
        showBusinessSegment: false// 是否显示所属业务板块隐藏
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();

      this.findProvisionBroadList()
    },
    methods: {
      ...mapGetters(['userInfo']),
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo).then((res) => {
          if (res.success) {
            that.model.purchaseBill = res.result// 单据编号
            that.model.bpmBizTitle = that.userName + '-' + that.model.purchaseBill// 标题
          }
        })
      },
      // 期望到货时间
      handleExpectUseTimeChange (mom, dateStr) {
        this.modelExpectUseTime = dateStr
      },
      disabledExpectUseTime (current) {
      // Can not select days before today and today
      return current && current <= moment().endOf('day');
    },
      add () {
        this.edit(this.modelDefault);
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.proposer = this.userInfo().empId; // 当前登录人
        this.model.proposerDeptId = this.userInfo().deptId; // 当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 申请时间
        this.$set(this.model, 'urgentStatus', 'no') // 默认为否
        // this.model.applicant = this.userInfo().employee.orgDepart; //当前登录人单位
        this.getBillNo() // 获取单据编号
      },
      edit (record) {
        this.$refs['form'].clearValidate();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.$refs.purchaseApply.loadData(1, this.model.id)
        } else {
          this.$refs.purchaseApply.dataSource = []
        }
        if (record.expectUseTime) {
          this.model.expectUseTime = moment(record.expectUseTime, 'YYYY-MM-DD HH:mm')
          this.modelExpectUseTime = record.expectUseTime
        } else {
          this.modelExpectUseTime = null
        }
        if (!!this.model.provisionBroadType && this.model.provisionBroadType == 'administration') {
          // 选择的是行政类隐藏
          this.showBusinessSegment = false;
        } else {
          // 选择的不是行政类
          this.showBusinessSegment = true;
        }
        this.provisionBroadups = this.model.provisionBroadType
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      // 采购大类
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      handleChange(item) {
        // 判断不为空
        if (!!this.model.provisionBroadType && !!item) {
          // 判断采购大类是否变化
          if (this.provisionBroadups !== item) {
            let details = this.$refs.purchaseApply.submitForm()
            if (details.length > 0) {
              const that = this;
              that.$confirm({
                title: '是否确认',
                content: '是否确认切换物料类别，此操作将会清空物料明细中已填写的所有信息？',
                onOk() {
                  // 确认后进行改变
                  that.provisionBroadups = that.model.provisionBroadType
                  // 清空子表数据
                  that.$refs.purchaseApply.dataSource = []
                  that.$set(that.model, 'purchaseBudgetAmount', null)
                },
                onCancel() {
                  that.model.provisionBroad = that.provisionBroadups
                }
              });
            } else {
              this.provisionBroadups = item
            }
          }
        }
      },
      isHideBusinessSegment() {
        if (!!this.model.provisionBroadType && this.model.provisionBroadType == 'administration') {
            // 选择的是行政类
            this.showBusinessSegment = false;
            this.$set(this.model, 'businessSegment', null) // 选择行政类置空业务板块
            this.$set(this.model, 'urgentStatus', '') // 默认为空
          } else {
            // 选择的不是行政类
            this.showBusinessSegment = true;
            this.$nextTick(function() {
              this.$set(this.model, 'businessSegment', 'ZLYWYWBKFZR') // 选择业务类默认选择治理运维
              this.$set(this.model, 'urgentStatus', 'no') // 默认为否
            });
          }
          // 清空数据
          // this.$set(this.model,'businessSegment',null)
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id': res.id, 'categoryName': res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          let details = this.$refs.purchaseApply.submitForm()
          if (!details.length > 0) {
            this.$message.warning('请添加物料明细信息！');
            this.$emit('unButtonDisable');
            return
          }

          // 判断数据有没有填写数量或者预算价格
          var isAmount = details.some(item => !item.amount);
          var isBudgetAmount = details.some(item => item.budgetAmount === '' || item.budgetAmount === null);
          if (isAmount) {
            // 当为true说明有值领用数量没有填写
            this.$message.warning('请填写物料明细中的数量！');
            this.$emit('unButtonDisable');
            return false
          }
          if (isBudgetAmount) {
            // 当为true说明有值领用用途没有填写
            this.$message.warning('请填写物料明细中的预算价格！');
            this.$emit('unButtonDisable');
            return false
          }
          if (!(this.model.provisionBroadType == 'business') && this.model.isSupplier == 0 && this.model.purchaseBudgetAmount >= 10000) {
            this.$message.warning('当前采购总金额大于等于10000元，请走招标采购申请单！');
            this.$emit('unButtonDisable');
            return
          }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        let details = this.$refs.purchaseApply.submitForm() || []
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.detailList = details
        this.model.expectUseTime = this.modelExpectUseTime
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      applyDetailData(data) {
        this.details = data
        if (this.details.length > 0) {
          let count = 0
          this.details.forEach((item, index) => {
            count = count + (item.amount * item.budgetAmount)
          })
          this.$set(this.model, 'purchaseBudgetAmount', count)
        } else {
          this.$set(this.model, 'purchaseBudgetAmount', null)
        }
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#pruchaseContent',
          popTitle: '采购申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
